package cloud.maque.auth.service;

import cloud.maque.auth.model.Oauth2AccessTokenRes;
import cloud.maque.auth.model.Oauth2GetAccesstokenReq;
import cloud.maque.auth.model.Oauth2User;
import cloud.maque.common.core.consts.MediaTypes;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.util.HashMap;
import java.util.Objects;

public interface Oauth2CallBackService {

    default Oauth2AccessTokenRes getAccessToken(Oauth2GetAccesstokenReq accesstokenReq, String url) {

        //1. 创建http请求，构建请求体和请求url等，并向gitee发起请求
        MediaType mediaType = MediaTypes.JSON.getMediaType();
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON.toJSONString(accesstokenReq), mediaType);
        Request request = new Request.Builder()
                .header("Accept","application/json")
                .url(url)
                .post(body)
                .build();

        //2. 获取gitee对应的响应消息，根据消息解析出用户的 access token
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String tokenStr = Objects.requireNonNull(response.body()).string();
                return JSONObject.parseObject(tokenStr, Oauth2AccessTokenRes.class);

            } else {
                throw new RuntimeException(response.body().string());
            }
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    default HashMap getUserBase(String url, HashMap<String, Object> headers) {
        //1. 构建http的GET请求，向gitee请求用户数据
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                .url(url);
        if (headers != null) {
            headers.forEach((String key, Object value) -> {
                builder.header(key, (String) value);
            });
        }
        Request request = builder.build();

        //2. 获取gitee传回来的响应消息，根据消息解析出用户消息
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String giteeUserStr = Objects.requireNonNull(response.body()).string();
                return JSONObject.parseObject(giteeUserStr, HashMap.class);
            } else {
                throw new RuntimeException(response.body().string());
            }
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取AccessToken
     *
     * @param code
     * @return
     */
    Oauth2AccessTokenRes getAccessToken(String code);

    /**
     * 获取第三方的用户信息
     *
     * @param accessToken
     * @return
     */
    Oauth2User getUser(String accessToken);

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     */
    String refreshToken(String refreshToken);
}
